<template>
    <a-modal :keyboard="false" :maskClosable="false" title="转地产" :open="visible" :width="550" :confirmLoading="loading" centered @ok="handleSubmit" @cancel="handleCancel">
        <a-form layout="vertical">
            <a-row :gutter="16" type="flex" justify="start">
                <a-col :xs="24" :sm="24" :md="24" v-if="orderTypeSub == 0">
                    <a-form-item label="地产报修部位" v-bind="validateInfos.partId">
                        <a-select v-model:value="modelRef.partId" @change="handleChange" placeholder="请选择">
                            <a-select-option v-for="(item, index) in partList" :key="index" :value="item.partId">{{ item.partName }}</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="24">
                    <a-form-item label="地产报修分类" v-bind="validateInfos.detail">
                        <a-cascader
                            v-model:value="modelRef.detail"
                            :options="partClassList"
                            :field-names="{
                                children: 'detailList',
                                label: 'name',
                                value: 'id',
                            }"
                            style="width: 100%"
                            @change="handleCascaderChange"
                            placeholder="请选择"
                        />
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
    </a-modal>
</template>

<script lang="ts">
import type { PropType } from 'vue';
import { defineComponent, reactive, ref, watchEffect, watch } from 'vue';
import { Form, message } from 'ant-design-vue';
import { cloneDeep, isEmpty } from 'lodash-es';
import { transferOrderDC, getRoomPart, getRoomPartClass } from '@/api/order/mine-list';
import { dictDataListByDictType } from '@/api/user/dict';

export default defineComponent({
    props: {
        visible: {
            type: Boolean,
            required: true,
        },
        model: {
            type: Object as PropType<any>,
            default: () => null,
        },
    },
    emits: ['cancel', 'success'],
    setup(props, { emit }) {
        const loading = ref(false);
        const cateData = ref<any[]>([]);
        const defaultForm = {
            status: 1,
            classifyName: '',
            orderSource: '',
        };
        const modelRef = reactive<any>(cloneDeep(defaultForm));
        const rulesRef = reactive({
            partId: [{ required: true, message: '请选择' }],
            detail: [{ required: true, message: '请选择' }],
        });
        const { validateInfos, resetFields, validate } = Form.useForm(modelRef, rulesRef);
        const partList: any = ref([]);
        const partClassList: any = ref([]);

        // 记录初始值
        const initValues = reactive({});
        watch(
            () => props.visible,
            () => {
                Object.assign(initValues, cloneDeep(props.model));
            },
        );
        const orderTypeSub: any = ref('');
        watchEffect(() => {
            if (props.visible) {
                orderTypeSub.value = props.model.orderTypeSub;

                if (orderTypeSub.value == 0) {
                    getRoomPart(props.model.id).then(res => {
                        partList.value = res.data;
                    });
                }

                getRoomPartClass(orderTypeSub.value).then(res => {
                    res.data.forEach(item => {
                        item.id = item.partItemId;
                        item.name = item.partItemName;
                    });
                    partClassList.value = res.data;
                });
                if (props.model) {
                    Object.assign(modelRef, {
                        id: props.model.id,
                    });
                }
            }
        });

        const handleChange = (val, options) => {
            const current = partList.value.find(item => item.partId === val);
            modelRef.repairPart = current.partName;
        };

        const handleCascaderChange = (value: any, selectedOptions: any) => {
            modelRef.partItemId = selectedOptions[0].id;
            modelRef.firstRepairClassify = selectedOptions[0].name;

            modelRef.detailId = selectedOptions[1].id;
            modelRef.repairClassify = selectedOptions[1].name;
        };

        const handleCancel = () => {
            resetFields();
            Object.keys(modelRef).forEach(key => {
                delete modelRef[key];
            });
            Object.assign(modelRef, cloneDeep(defaultForm));

            modelRef.status = 1;
            emit('cancel');
        };

        const handleSubmit = async () => {
            validate().then(() => {
                loading.value = true;
                const { id: orderId, partId, repairPart, partItemId, firstRepairClassify, detailId, repairClassify } = modelRef;
                transferOrderDC({
                    orderId,
                    partId,
                    repairPart,
                    partItemId,
                    firstRepairClassify,
                    detailId,
                    repairClassify,
                })
                    .then(res => {
                        if (res.data) {
                            message.success('操作成功');
                            emit('success');
                            handleCancel();
                        }
                    })
                    .finally(() => {
                        loading.value = false;
                    });
            });
        };
        return {
            orderTypeSub,
            loading,

            modelRef,
            validateInfos,
            resetFields,

            handleSubmit,
            handleCancel,
            handleCascaderChange,
            initValues,
            cateData,
            isEmpty,
            handleChange,

            partList,
            partClassList,
        };
    },
    components: {},
});
</script>
